<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!--  separator-class="el-icon-arrow-right"：设置面包屑中间的连接图标 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert
        title="修改商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form
        :rules="editFormRules"
        :model="editForm"
        ref="editFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="handleTabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="editForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="editForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="editForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="editForm.goods_cat"
                :props="cascaderProps"
                :options="ParamsList"
                expandTrigger="hover"
                @change="handleChange"
                clearable
                :disabled="true"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableDate"
              :key="item.vals_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_values">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_values"
                  :key="cb.vals_id"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染表单的item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableDate"
              :key="item.id"
            >
              <!-- 文本输入框 -->
              <el-input v-model="item.attr_values"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:3301/api/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleChangeImg"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
              :file-list="fileList"
            >
              <!-- action:上传地址，on-cheange：选择图片，
              on-remove：删除图片，on-preview：预览图片，
              headers：上传图片的请求头，on-success：上传成功事件-->
              <!-- list-type="picture":图片预览的方式 -->
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编译器组件 -->
            <quill-editor v-model="editForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="addBtn" @click="editGoods"
              >修改商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previeVisible" width="40%">
      <img :src="previePath" alt="" class="previeImg" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      activeIndex: '0',
      //  图片预览对话框
      previeVisible: false,
      //  图片路径
      previePath: '',
      //  修改信息的表单的规则
      editFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      //    修改商品信息表单
      editForm: {
        goods_name: '',
        goods_weight: 0,
        goods_price: 0,
        goods_number: 0,
        //  商品的分类
        goods_cat: [],
        //  图片的数组
        pics: [],
        //  商品的详情介绍
        goods_introduce: '',
        //  动态参数和静态属性
        attrs: []
      },
      //  上传的图片列表
      fileList: [],
      //   参数列表
      ParamsList: [],
      //  指定级联选择器的配置属性
      cascaderProps: {
        value: 'id',
        label: 'cat_name',
        children: 'children'
      },
      //    动态参数列表数据
      manyTableDate: [],
      //    静态属性列表数据
      onlyTableDate: [],
      //  图片上传组件的headers请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      }
    }
  },
  methods: {
    //  获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.ParamsList = res.data
    },
    //  级联选择器选中选项事件
    handleChange () {},
    // 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
    handleTabs (newActive, lodActive) {
      if (this.editForm.goods_cat.length !== 3 && lodActive === '0') {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    //  选择图片
    handleChangeImg (file, fileList) {},
    //  预览图片
    handlePreview (file) {
      this.previeVisible = true
      this.previePath = file.url
    },
    //  删除图片
    handleRemove (file, fileList) {
      const index = this.fileList.findIndex((item) => item.uid === file.uid)
      this.fileList.splice(index, 1)
      console.log(this.fileList)
      console.log(this.editForm)
    },
    //  上传图片成功
    handleSuccess (res) {
      this.fileList.push({ url: res.data.url, name: res.data.url })
      console.log(this.fileList)
    },
    //  根据id获取信息
    async getGoodsById () {
      const id = this.$route.query.goods_id
      const { data: res } = await this.$http.get(`goods/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品信息失败')
      }
      console.log(res.data)
      res.data.goods_cat = res.data.goods_cat.split(',')
      const attr = []
      res.data.goods_cat.forEach((item) => {
        attr.push(parseInt(item))
      })
      res.data.goods_cat = attr
      console.log(res.data.goods_cat)
      this.editForm = res.data
      this.editForm.attr.forEach((item) => {
        if (item.attr_sel === 'many') {
          if (!item.attr_values) return
          item.attr_values = item.attr_values.split(' ')
          this.manyTableDate.push(item)
        }
        if (item.attr_sel === 'only') {
          this.onlyTableDate.push(item)
        }
      })
      if (this.editForm.pic !== '') {
        this.editForm.pic = this.editForm.pic.split(',')
        this.editForm.pic.forEach((item) => {
          this.fileList.push({ url: item, name: item })
        })
      }
    },
    //  修改商品信息
    async editGoods () {
      const goodsId = this.$route.query.goods_id
      this.editForm.attrs = []
      //  处理动态参数
      this.manyTableDate.forEach((item) => {
        const newInfo = {
          attr_id: item.id,
          attr_value: item.attr_values
        }
        this.editForm.attrs.push(newInfo)
      })
      //  处理静态属性
      this.onlyTableDate.forEach((item) => {
        const newInfo = {
          attr_id: item.id,
          attr_value: item.attr_values
        }
        this.editForm.attrs.push(newInfo)
      })
      const arr = []
      this.fileList.forEach((item) => {
        arr.push(item.url)
      })
      this.editForm.pic = arr
      console.log(this.editForm)
      const { data: res } = await this.$http.put(
        `goods/${goodsId}`,
        this.editForm
      )
      if (res.meta.status === 205) return this.$message.error(res.meta.msg)
      if (res.meta.status !== 200) return this.$message.error('修改商品失败')
      this.$message.success('修改商品信息成功')
      this.$router.push('/goods')
    }
  },
  created () {
    this.getCateList()
    this.getGoodsById()
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px;
}
.el-step__title {
  font-size: 13px;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previeImg {
  width: 100%;
}
.addBtn {
  margin-top: 15px !important;
}
</style>
